<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :tname="tname"
          :param="param"
          :leftTreeParentId="0"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
      </template>
      <template slot="chart">
        <ChartM
          v-if="datatype !== -1"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
        />
        <!-- <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText"/>
        </div> -->
      </template>
      <template slot="type">
        <!-- <i class="icon el-icon-download" @click="exportData">导出数据</i> -->
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
      </template>
    </c-slot>

    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item" :key="j">{{ ite }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartM from "../charts/ChartM";
import {
  refactor,
  getYear,
  downloadChartImg,
  transCNCountry,
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object,
    },
    dcData: {
      type: Object,
    },
  },
  components: {
    CSlot,
    ChartM,
    ChooseScreen,
  },
  data() {
    return {
      loading: false,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      charttype: -1, // 图表类型
      selectATit: "", // 筛选条件A，动态
      timeType: "", // 设置时间筛选类型
      chartId: "", // 图表id名称
      datatype: -1, // 图表数据类型
      chartData: [],
      chartType: "line",
      dom: {},
      tableData: {
        tit: [],
        content: [],
      },
      yearArr: [],
      emptyText: "数据加载中...",
    };
  },
  computed: {
    ...mapState(["searchWord"]),
  },
  watch: {
    // chartTempl() {
    //   this.init();
    // },
    dcData() {
      this.init();
    },
  },
  mounted() {
    // this.init();
  },
  methods: {
    init() {
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.charttype = this.chartTempl.tdata.charttype;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      if (this.dcData && this.dcData.chartData) {
        let data = JSON.parse(JSON.stringify(this.dcData.chartData));
        this.loading = false;
        data.forEach((v) => {
          v.key = transCNCountry(v.key);
        });
        refactor({
          type: 5, // 根据后台返回的datatype，判断数据解析格式
          data,
          callback: (refactor) => {
            this.chartData = [refactor] || [];
            // this.yearArr = refactor.yearArr
            // // 表格
            // this.tableData.tit = ['序列号', this.selectATit, ...this.yearArr]
            // this.tableData.content = refactor.dataArr
          },
        });
      } else {
        this.emptyText = "暂无数据";
      }
      // let {startYear, endYear} = getYear(10)
      // this.startYear = String(startYear)
      // this.endYear = String(endYear)
      // this.getChartData({
      //   startYear:this.startYear,
      //   endYear:this.endYear,
      //   timeType:this.timeType,
      //   param:this.param
      // })
    },
    getChartData(Params) {
      let ths = this;
      if (this.cancel !== null) {
        this.cancel();
      }

      let sq = `${Params.timeType}/${Params.startYear}-01-01 to ${Params.endYear}-12-31`;
      if (this.searchWord !== "") {
        sq = `${this.searchWord} and ` + sq;
      }

      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: [],
      };

      let params = {
        ...Params.param,
        sq: sq,
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      this.$post(this.$Url.analysis.invoke, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        }),
      })
        .then((res) => {
          let data = res.data;
          this.$store.commit("setTotalTxt", data.total);
          if (data) {
            this.loading = false;
            data.forEach((v) => {
              v.key = transCNCountry(v.key);
            });
            refactor({
              type: 5, // 根据后台返回的datatype，判断数据解析格式
              data,
              callback: (refactor) => {
                this.chartData = [refactor] || [];
                this.yearArr = refactor.yearArr;
                // 表格
                this.tableData.tit = [
                  "序列号",
                  this.selectATit,
                  ...this.yearArr,
                ];
                this.tableData.content = refactor.dataArr;
              },
            });
          } else {
            this.emptyText = "暂无数据";
          }
        })
        .catch((err) => {
          this.emptyText = "暂无数据";
        });
    },

    disabledDate(time, year, type) {
      if (type === "gt") {
        if (year && year !== "") {
          if (time.getFullYear() > Number(year)) {
            return true;
          }
          return false;
        }
      } else if (type === "lt") {
        if (year && year !== "") {
          if (time.getFullYear() < Number(year)) {
            return true;
          }
          return false;
        }
      }
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws =
        XLSX.utils.aoa_to_sheet(aoa); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    },
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  },
};
</script>

<style lang="scss">
</style>